package com.yonyong.tao.parts.readfile;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

/**
 * @Describtion Todo
 * @Author yonyong
 * @Date 2020/3/31 14:55
 * @Version 1.0.0
 **/
public class ReadJson {
    public static void main(String[] args) throws IOException {
        String json = readJsonData("json/category.json");
        System.out.println(json);

        final ObjectMapper mapper = new ObjectMapper();
        List list = mapper.readValue(json,List.class);
        for (Object o :list){
            HashMap map = (HashMap) o;
            System.out.println(map.get("id"));
            String id = String.valueOf( map.get("id"));
            String pid = String.valueOf( map.get("pid"));
            String name = String.valueOf( map.get("name"));
            String picture = String.valueOf( map.get("picture"));
        }
    }

    /**
     * 读取json文件
     */
    public static String readJsonData(String filePath){
        URL url= ReadJson.class.getClassLoader().getResource(filePath);
        assert url != null;
        String path = url.getPath();
        File jsonFile = new File(path);
        try {
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
